package com.small.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.small.proxy.Proxy;
import net.sf.json.JSONObject;

public class BaseUtil {
  
  private static Logger logger = Logger.getLogger(BaseUtil.class);

  /**
   * 使用循环判断arr是否包含value 包含返回true
   * @param value
   * @return
   */
  public static boolean useLoop(String value) {
      List<String> arr = new ArrayList<String>();
      Collections.addAll(arr, "html", "js", "css", "png", "jpg", "txt" , "Images", "page", "upload",
              "woff", "ttf", "font", "xsls");
      Iterator<String> it = arr.iterator();
      while (it.hasNext()) {
          if (value.endsWith(it.next()))
              return true;
      }
      return false;
  }

  /**
   * 计算总页
   * @param totalNumber  总条
   * @param limit   每页条数
   * @return
   */
  public static int getTotalPage(int totalNumber, int limit){
      int totalPage = totalNumber%limit > 0 ? totalNumber/limit + 1 : totalNumber/limit;
      return totalPage;
  }

  /**
   * 传boolean类型数据，返回JSONObject  result数据
   * @param boo
   * @return
   */
  public JSONObject getJsonResult(boolean boo){
      JSONObject result = new JSONObject();
      if (boo)
          result.put("result", "success");
      if (!boo)
          result.put("result", "fail");

      return result;
  }

  /**
   * 获取全小写没有-的uuid
   * @return
   */
  public static String getUUID(){
      String uuid = UUID.randomUUID().toString().replace("-", "");
      return uuid;
  }

  /**
   * 获取全大写没有-的uuid
   * @return
   */
  public static String getUUID2(){
      String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
      return uuid;
  }

  /**
   * 获取系统当前时间  <br/>
   * 格式为---yyyy-MM-dd HH:mm:ss
   * @return
   */
  public static String getTime(){
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String time = format.format(new Date());
      return time;
  }
  
  /**文件分隔符问题<br/>
   * 文件分隔符Linux与Windows统一
   * @param path  路径
   * @return
   */
  public static String pathSeparator(String path) {
    //windows下
    if("\\".equals(File.separator)){
        path = path.replace("/", "\\");
    }
    //linux下
    if("/".equals(File.separator)){
        path = path.replace("\\", "/");
    }
    return path;
  }
  
  /**
   * 文件转输出流 ByteArrayOutputStream
   * @param file
   * @return
   * @throws IOException
   */
  @SuppressWarnings("resource")
  public static ByteArrayOutputStream fileParseOutput(File file) throws IOException {
    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
    int ch;
    while ((ch = new FileInputStream(file).read()) != -1) {
      oStream.write(ch);
    }
    return oStream;
  }
  
  /**
   * 输入流转输出流  InputStream转OutputStream
   * @param inputStream
   * @return
   * @throws IOException
   */
  public static ByteArrayOutputStream InputParseOutput(InputStream inputStream) throws IOException {
    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
    int ch;
    while ((ch = inputStream.read()) != -1) {
      oStream.write(ch);
    }
    return oStream;
  }
  
  /**
   * 输出流转输入流  outputStream 转InputStream
   * @param outputStream
   * @return
   */
  public static ByteArrayInputStream OutputParseInput(OutputStream outputStream) {
    ByteArrayOutputStream arrayOutputStream = (ByteArrayOutputStream) outputStream;
    byte[] binary = arrayOutputStream.toByteArray();
    ByteArrayInputStream inputStream = new ByteArrayInputStream(binary);
    return inputStream;
  }
  
  /**
   * 输出流转二进制数组  outputStream 转bintry
   * @param outputStream
   * @return
   */
  public static byte[] OutputParseBinary(OutputStream outputStream) {
    ByteArrayOutputStream arrayOutputStream = (ByteArrayOutputStream) outputStream;
    byte[] binary = arrayOutputStream.toByteArray();
    return binary;
  }
  
  /**
   * 文件转数组  file转byte[]
   * @param file
   * @return
   * @throws FileNotFoundException
   * @throws IOException
   */
  public static byte[] fileParseBinary(File file) throws FileNotFoundException, IOException {
    byte[] data = null;
    
    try {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int len;
        byte[] buffer = new byte[1024];
        while ((len = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }

        data = baos.toByteArray();
        fis.close();
        baos.flush();
        baos.close();
    } catch (Exception e) {
      logger.error(e.toString());
    }
    return data;
  }
  
  /**
   * 数组转换Set集合  对增删改都没有任何影响
   * @param mclass  需要转换的类数组
   * @return
   */
  public static Set<Class<?>> ArrayChangeSet(Class<?>[] mclass) {
    Set<Class<?>> list = new HashSet<Class<?>>(mclass.length);
    Collections.addAll(list, mclass);
    return list;
  }
  
  /**
   * 数组转换Set集合  对增删改都没有任何影响  并且实例化class
   * @param mclass  需要转换的类数组
   * @return
   */
  public static Set<Proxy> ArrayChangeNewSet(Class<?>[] mclass) {
    Set<Proxy> proxies = new HashSet<Proxy>();
    for (Class<?> clazz : mclass) {
      try {
        proxies.add((Proxy) clazz.newInstance());
      } catch (InstantiationException e) {
        logger.error(e.toString());
      } catch (IllegalAccessException e) {
        logger.error(e.toString());
      }
    }
    return proxies;
  }
  
  /**
   * *获取map中同一个value的所有key
   * @param <V>     Map第一个参数类型
   * @param <V>     Map第二个参数类型
   * @param map     需要操作的Map
   * @param value   需要判断的固定value
   * @return 
   * @return
   */
  public static <K, V> Set<K> getMapKey(Map<K, V> map, V value) {
    Set<K> set = new HashSet<K>();
    for (Entry<K, V> entry : map.entrySet()) {
      
      try {
        if (entry.getValue().equals(value)) {
          set.add(entry.getKey());
        }
      } catch (Exception e) {
        logger.error(e.toString());
      }
      
    }
    return set;
  }
  
  /**
   * 取出set1和set2中的交集
   * @param <T>  
   * @param set1  
   * @param set2
   * @return
   */
  public static <T> Set<T> getIntersection(Set<T> set1, Set<T> set2) {
    Set<T> result = new HashSet<T>();
    result.clear();
    result.addAll(set1);
    result.retainAll(set2);
    return result;
  }
  
}
